package com.spring.data.jpa.repository.imp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;

import com.spring.data.jpa.domain.User;
import com.spring.data.jpa.repository.UserRepositoryCustom;

public class UserRepositoryImpl implements UserRepositoryCustom{
	
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * Configure the entity manager to be used.
	 * 
	 * @param em the {@link EntityManager} to set.
	 */
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	//@Override
	public Map<String, Object> searchByCondition(int page,int start,int limit,User user) {
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		String countsql = "select count(*) from t_user u where 1=1";
		String listsql = "select * from t_user u where 1=1";
		String conditons = "";
 		if(StringUtils.isNotBlank(null==user.getId()?null:user.getId().toString())){
 			conditons += " and u.id = " + user.getId();
		}
 		if(StringUtils.isNotBlank(user.getName().toString())){
 			conditons += " and u.name = '" + user.getName()+"'";
 		}
 		if(StringUtils.isNotBlank(user.getAccount().toString())){
 			conditons += " and u.account = '" + user.getAccount()+"'";
 		}
 		if(StringUtils.isNotBlank(user.getPassword().toString())){
 			conditons += " and u.password = '" + user.getPassword()+"'";
 		}
		Query queryCount = em.createNativeQuery(countsql+conditons);
		Query queryList = em.createNativeQuery(listsql+conditons, User.class).setFirstResult(start).setMaxResults(limit);
		
		Object count = queryCount.getSingleResult();
		@SuppressWarnings("unchecked")
		List<User> userList = queryList.getResultList();
		
		returnMap.put("count", count);
		returnMap.put("rows", userList);
		return returnMap;
	}
}
